﻿/*
Copyright (c) 2010, hiSoft
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the hiSoft nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE HISOFT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL HISOFT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Text;
using System.IO;

namespace Orchard.Test.Library
{
    public class ModuleHelper : UIHelperBase
    {
        public ModuleHelper(TestLibrary settings) : base(settings) { }

        private string GetFeatureActionLocator(string featureId)
        {
            return String.Format("//li[@id='{0}']/div/div[2]/a", featureId);   // a or form/button
        }

        public string GetExpectedFeatureIdByName(string featureName)
        {
            StringBuilder featureId = new StringBuilder();
            featureId.Append(featureName.Substring(0, 1).ToLower());
            for (int i = 1; i < featureName.Length; i++)
            {
                Char c = featureName[i];
                if (c == ' ')
                {
                    featureId.Append('-');
                }
                else
                {
                    if (Char.IsUpper(c))
                    {
                        Char c1 = featureName[i - 1];
                        if (Char.IsLower(c1))
                        {
                            featureId.Append('-');
                        }
                    }
                    featureId.Append(c.ToString().ToLower());
                }
            }
            featureId.Append("-feature");
            return featureId.ToString();
        }

        public void ManageFeatures()
        {
            if (!selenium.GetLocation().EndsWith("/Admin/Modules/Features"))
            {
                selenium.Open("/Admin/Modules/Features");
            }
        }

        public void ManageInstalled()
        {
            if (!selenium.GetLocation().EndsWith("/Admin/Modules"))
            {
                selenium.Open("/Admin/Modules");
            }
        }        

        public bool IsFeaturePresent(string featureName)
        {
            ManageFeatures();
            return selenium.IsTextPresent(featureName);
        }

        public void DoActionToFeatureOnManageFeatures(string featureId, FeatureAction featureAction)
        {
            string actionText = Enum.GetName(typeof(FeatureAction), featureAction);
            string actionLocator = GetFeatureActionLocator(featureId);
            string actualActionText = selenium.GetText(actionLocator);
            if (actualActionText == actionText)
            {
                ClickAndWait(actionLocator);              
            }
        }
      
        public void DoActionToFeature(string featureId, FeatureAction featureAction)
        {
            ManageFeatures();
            DoActionToFeatureOnManageFeatures(featureId, featureAction);
        }

        public FeatureStatus GetFeatureStatusOnManageFeatures(string featureId)
        {
            string actionLocator = GetFeatureActionLocator(featureId);
            string actualActionText = selenium.GetText(actionLocator);
            if (actualActionText == "Enable")
            {
                return FeatureStatus.Disabled;
            }
            else
            {
                return FeatureStatus.Enabled;
            }
        }

        public FeatureStatus GetFeatureStatus(string featureId)
        {
            ManageFeatures();
            return GetFeatureStatusOnManageFeatures(featureId);
        }

        public void EnableArchiveLater()
        {
            DoActionToFeature("orchard-archive-later-feature", FeatureAction.Enable);
        }

        public void DisableBlogs()
        {
            DoActionToFeature("orchard-blogs-feature", FeatureAction.Disable);
        }

        public void EnableBlogs()
        {
            DoActionToFeature("orchard-blogs-feature", FeatureAction.Enable);
        }

        public void EnableIndexing()
        {
            DoActionToFeature("orchard-indexing-feature", FeatureAction.Enable);
        }

        public void EnableLucene()
        {
            DoActionToFeature("lucene-feature", FeatureAction.Enable);
        }

        public void DisableLucene()
        {
            DoActionToFeature("lucene-feature", FeatureAction.Disable);
        }

        public void EnableSearch()
        {
            DoActionToFeature("orchard-search-feature", FeatureAction.Enable);
        }

        public void EnableAllSearchFeature()
        {
            EnableLucene();
            EnableSearch();
        }

        public void DisableAllSearchFeature()
        {
            DisableLucene();
            DoActionToFeature("orchard-indexing-feature", FeatureAction.Disable);
        }       

        public void EnableLists()
        {
            DoActionToFeature("orchard-lists-feature", FeatureAction.Enable);
        }

        public void EnableMultiTenancy()
        {
            DoActionToFeature("orchard-multi-tenancy-feature", FeatureAction.Enable);
        }

        public void EnablePackaging()
        {            
            DoActionToFeature("orchard-packaging-feature", FeatureAction.Enable);
        }

        public void EnablePackageUpdates()
        {            
            DoActionToFeature("gallery-updates-feature", FeatureAction.Enable);
        }        

        public void EnableGallery()
        {
            DoActionToFeature("gallery-feature", FeatureAction.Enable);
        }

        public void EnableEmail()
        {
            DoActionToFeature("orchard-email-feature", FeatureAction.Enable);
        }

        public void EnableWebCommandline()
        {
            DoActionToFeature("orchard-experimental-web-command-line-feature", FeatureAction.Enable);
        }

        public void EnableLocalization()
        {
            DoActionToFeature("orchard-localization-feature", FeatureAction.Enable);
        }

        public void EnableTestingLists()
        {
            DoActionToFeature("orchard-experimental-testing-lists-feature", FeatureAction.Enable);
        }

        public void EnableImportExport()
        {
            DoActionToFeature("orchard-import-export-feature", FeatureAction.Enable);
        }

        public void EnableWarmup()
        {
            DoActionToFeature("orchard-warmup-feature", FeatureAction.Enable); 
        }

        public void EnableCodeGeneration()
        {
            DoActionToFeature("orchard-code-generation-feature", FeatureAction.Enable);
        }
        
        public void EnableRemoteBlogPublishing()
        {
            DoActionToFeature("orchard-blogs-remote-publishing-feature", FeatureAction.Enable);
        }

        public void EnableScriptingDLR()
        {
            DoActionToFeature("orchard-scripting-dlr-feature", FeatureAction.Enable);
        }

        public void DisableScriptingDLR()
        {
            DoActionToFeature("orchard-scripting-dlr-feature", FeatureAction.Disable);
        }

        public void DisableLightWeightScripting()
        {
            DoActionToFeature("orchard-scripting-lightweight-feature", FeatureAction.Disable);
        }

        public int GetModuleIndexOfPageByNameInGallery(string strModuleName)
        {
            int moduleCountOnPage = (int)selenium.GetXpathCount(UIHelperBase.ModulesListLocatorInGallery);           
            string moduleName = "";
            int moduleIndex = -1;
            for (int i = 1; i <= moduleCountOnPage; i++)
            {
                moduleName = selenium.GetText(string.Format("{0}[{1}]/div/div/div/a/h2", UIHelperBase.ModulesListLocatorInGallery, i));
                if (moduleName.Contains(strModuleName))
                {
                    moduleIndex = i;
                    break;
                }
            }
            return moduleIndex;
        }

        public void DeleteModuleFolderInDisk(string strModuleFolderName)
        {
            string modulePath = string.Format("{0}\\{1}", TestLibrary.Consts.OrchardModulesPath, strModuleFolderName);
            try
            {
                if (Directory.Exists(modulePath))
                    Directory.Delete(modulePath, true);
            }
            catch (Exception)
            { ;}
                     
        }

        public void RefreshAndGoToPageOfFindModule(string strFindModuleName)
        {
            selenium.SetTimeout("60000");
            selenium.Open("/Packaging/Gallery/Modules");
            while (!selenium.IsElementPresent(string.Format("//a[contains(@href, '/InstallGallery?packageId=Orchard.Module.{0}')]",strFindModuleName)))
                ClickAndWait("link=>");
        }
    }

    public enum FeatureAction
    {
        Enable,
        Disable
    }

    public enum FeatureStatus
    {
        Enabled,
        Disabled
    }
}
